package cn.ronghuanet.org.service.impl;

import cn.ronghuanet.basic.service.impl.BaseServiceImpl;
import cn.ronghuanet.basic.utils.PageList;
import cn.ronghuanet.org.domain.Department;
import cn.ronghuanet.org.mapper.DepartmentMapper;
import cn.ronghuanet.org.query.DepartmentQuery;
import cn.ronghuanet.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 业务的service实现类中,需要实现IDepartmentSerivce 接口,继承BaseServiceImpl实现类
 * 实现IDepartmentSerivce 接口 是因为它里面会定义自己独有的业务方法
 * 继承BaseServiceImpl实现类 是为了继承公共的方法,公共方法就可以不用写了
 */
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)      // 是要写 写的事务?只读事务?
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 如果这个公共方法不止是调用mapper,而还有自己的业务逻辑的话,就可以重写该方法,写自己的业务逻辑即可
     * @param department
     */
    @Override
    @Transactional
    public void add(Department department) {
        // 在新增的时候,要在后端处理创建时间,创建时间要获取系统时间
        department.setCreateTime(new Date());
        departmentMapper.insert(department);
        // 处理path字段
        // 判断当前要新增的部门是不是一级部门,如果是一级部门,path = /自己的id
        // 如果不是一级部门,path = 父部门的path+/+自己的id
        String path = "";
        if(Objects.isNull(department.getParent()) || Objects.isNull(department.getParent().getId())){ // 父部门为空,说明当前新增的是一个一级部门,没有父部门
            path = "/"+department.getId();
        }else{
            // 说明它有父部门,path = 父部门的path+/+自己的id
            Long parentId = department.getParent().getId();
            Department parent = departmentMapper.loadById(parentId);
            path = parent.getPath()+"/"+department.getId();
        }
        department.setPath(path);
        departmentMapper.update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        // 修改时间,也要获取当前系统时间
        department.setUpdateTime(new Date());

        String path = "";
        if(Objects.isNull(department.getParent())){ // 父部门为空,说明当前新增的是一个一级部门,没有父部门
            path = "/"+department.getId();
        }else{
            // 说明它有父部门,path = 父部门的path+/+自己的id
            Long parentId = department.getParent().getId();
            Department parent = departmentMapper.loadById(parentId);
            path = parent.getPath()+"/"+department.getId();
        }
        department.setPath(path);
        departmentMapper.update(department);
    }

    @Override
    public List<Department> tree() {
        return departmentMapper.tree();
    }
}
